const xlsx = require("node-xlsx")
const path = require("path");
const uuid = require("uuid");
const user = require("../sql/user")
const sql = require("../sql/index");
const { renameSync } = require("fs");

const fs = require("fs");

module.exports = function(){
    return (req, res, next)=>{

        console.log(req.files[0]);

        const oldName = path.join(__dirname, "..", req.files[0].path);
        const newName = oldName + "-" + req.files[0].originalname;
        // 改名
        fs.rename(oldName, newName, ()=>{

            // if(){}

            const p = path.join(newName);

            const data = xlsx.parse(p);

            // if(){}

            const arr = [];
            data[0].data.forEach(val=>{
                arr.push({
                    userid: "user" + uuid.v1(),
                    username: val[0],
                    password: val[1],
                    regTime: Date.now(),
                    isLogin:0,
                    token:""
                })
            })

            sql.add(user, arr, ()=>{
                res.send(JSON.stringify({
                    code:1,
                    msg:"导入成功"
                }));
            })

        });
    }
}
